<?php

require_once( ARROW_LIBS_PATH.'/smarty/Smarty.php' );

class SmartyCompiler{

	/**
	 * Smarty instance
	 *
	 * @var Smarty
	 */
	public $smartyInstance;
	public $content;
	
	private static $selfSmartyInstance;
	
	
	public function __construct( $content, Smarty $smartyI = null ){
		$this->content = $content;
		if($smartyI != null)
			$this->smartyInstance = $smartyI;
		else{
			if(self::$selfSmartyInstance == null){
				$this->smartyInstance = new Smarty();
				$this->smartyInstance->template_dir = ARROW_CACHE_PATH."/templates/src/";
				$this->smartyInstance->compile_dir = ARROW_CACHE_PATH."/templates/compiled/";
				$this->smartyInstance->cache_dir = ARROW_CACHE_PATH."/templates/cache/";
				self::$selfSmartyInstance = $this->smartyInstance;
			}else{
				$this->smartyInstance = self::$selfSmartyInstance;
			}
		}
		
		$this->smartyInstance->force_compile = true;

		// register the resource name "string"
		$this->smartyInstance->register_resource("string", array( 
			array( $this, 'getTemplate' ),
			array( $this, 'getTimestamp' ),
			array( $this, 'getSecure' ),
			array( $this, 'getTrusted' )
		));
	}

	public function assign($var, $value = false){
		$this->smartyInstance->assign($var, $value);
	}

	public function getResult( $data = array() ){
		$this->smartyInstance->assign( $data );
		$hash = substr(md5($this->content),0,5).strlen($this->content);
		return $this->smartyInstance->fetch( "string:".$hash);
	}


	// put these function somewhere in your application
	function getTemplate ($tpl_name, &$tpl_source, &$smarty_obj){
		$tpl_source = $this->content;
		return true;
	}

	function getTimestamp($tpl_name, &$tpl_timestamp, &$smarty_obj){
		$tpl_timestamp = time()-1000;
		return true;
	}

	function getSecure($tpl_name, &$smarty_obj)     {
		// assume all templates are secure
		return true;
	}

	function getTrusted($tpl_name, &$smarty_obj){
		// not used for templates
	}

}
?>
